package com.cn.zy.hr.redis.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;

import java.nio.charset.Charset;
import java.util.Objects;

/**
 * @author zhangyi
 * @date 2018/11/28 20:56
 */
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset CHARSET_DEFAULT = Charset.forName("UTF-8");

    private Class<T> clazz;

    public FastJson2JsonRedisSerializer(Class<T> clazz) {
        this.clazz = clazz;
    }

    /**
     * serialize Object
     *
     * @param t
     * @return
     * @throws SerializationException
     */
    @Nullable
    @Override
    public byte[] serialize(@Nullable T t) throws SerializationException {
        if(Objects.isNull(t)){
            return null;
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(CHARSET_DEFAULT);
    }

    @Nullable
    @Override
    public T deserialize(@Nullable byte[] bytes) throws SerializationException {
        if(bytes == null || bytes.length == 0){
            return null;
        }
        String s = new String(bytes, CHARSET_DEFAULT);
        return JSON.parseObject(s,clazz);
    }
}
